package cn.signalpha.modules.resource.endpoint;

import cn.signalpha.common.constant.AppConstant;
import cn.signalpha.core.boot.file.LocalFile;
import cn.signalpha.core.boot.file.LocalFileUtil;
import cn.signalpha.core.log.exception.ServiceException;
import cn.signalpha.core.oss.model.OssFile;
import cn.signalpha.core.oss.model.PutFile;
import cn.signalpha.core.secure.annotation.PreAuth;
import cn.signalpha.core.tool.api.R;
import cn.signalpha.core.tool.constant.RoleConstant;
import cn.signalpha.core.tool.utils.FileUtil;
import cn.signalpha.core.tool.utils.Func;
import cn.signalpha.core.tool.utils.ObjectUtil;
import cn.signalpha.modules.resource.builder.oss.OssBuilder;
import cn.signalpha.modules.resource.entity.Attach;
import cn.signalpha.modules.resource.entity.AttachCategory;
import cn.signalpha.modules.resource.service.IAttachCategoryService;
import cn.signalpha.modules.resource.service.IAttachService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 对象存储端点
 */
@RestController
@AllArgsConstructor
@RequestMapping(AppConstant.APPLICATION_RESOURCE_NAME + "/oss/endpoint")
@Api(value = "对象存储端点", tags = "对象存储端点")
public class OssEndpoint {

	/**
	 * 对象存储构建类
	 */
	private final OssBuilder ossBuilder;

	/**
	 * 附件表服务
	 */
	private final IAttachService attachService;

	/**
	 * 附件表服务
	 */
	private final IAttachCategoryService attachCategoryService;

	@SneakyThrows
	@PostMapping("/put/file")
	@ApiOperation(value = "上传文件 - OSS", notes = "上传到OSS")
	public R<PutFile> putFile(@RequestParam MultipartFile file, @RequestParam(required = false) Long categoryId) {
		PutFile putFile = ossBuilder.template().putFile(file.getOriginalFilename(), file.getInputStream());
		Long attachId = buildAttach(file.getOriginalFilename(), file.getSize(), putFile, categoryId);
		putFile.setAttachId(attachId);
		return R.data(putFile);
	}

	@SneakyThrows
	@PostMapping("/upload/file")
	@ApiOperation(value = "上传文件 - 服务器", notes = "上传到服务器")
	public R<PutFile> upload(@RequestParam MultipartFile file, @RequestParam(required = false) Long categoryId) {
		LocalFile localFile = LocalFileUtil.getFile(file);
		localFile.transfer();
		PutFile putFile = new PutFile();
		putFile.setLink(localFile.getDomain().concat(localFile.getUploadVirtualPath()));
		putFile.setOriginalName(localFile.getOriginalFileName());
		putFile.setName(localFile.getUploadVirtualPath());
		putFile.setDomain(localFile.getDomain());
		if(ObjectUtil.isNotEmpty(categoryId) && categoryId != 0){
			Long attachId = buildAttach(file.getOriginalFilename(), file.getSize(), putFile, categoryId);
			putFile.setAttachId(attachId);
		}
		return R.data(putFile);
	}

	@SneakyThrows
	@PostMapping("/put/file/debug")
	@ApiOperation(value = "上传文件 - 调式", notes = "上传到OSS")
	public R<PutFile> putFile(@RequestParam MultipartFile file, @RequestParam(required = false) String code) {
		return R.data(ossBuilder.template(code).putFile(file.getOriginalFilename(), file.getInputStream()));
	}

	/**
	 * 构建附件表
	 *
	 * @param fileName  文件名
	 * @param fileSize  文件大小
	 * @param putFile 对象存储文件
	 * @return attachId
	 */
	private Long buildAttach(String fileName, Long fileSize, PutFile putFile, Long categoryId) {
		String fileExtension = FileUtil.getFileExtension(fileName);
		Attach attach = new Attach();

		attach.setCategoryId(categoryId);
		if(ObjectUtil.isEmpty(categoryId) || categoryId == 0){
			AttachCategory attachCategory = attachCategoryService.getOne(
				Wrappers.<AttachCategory>lambdaQuery().eq(AttachCategory::getCode, "other"));
			if(ObjectUtil.isEmpty(attachCategory)){
				attachCategory = new AttachCategory();
				attachCategory.setName("其他");
				attachCategory.setCode("other");
				attachCategory.setSort(-1);
				attachCategoryService.save(attachCategory);
			}
			attach.setCategoryId(attachCategory.getId());
		}
		attach.setDomain(putFile.getDomain());
		attach.setLink(putFile.getLink());
		attach.setName(putFile.getName());
		attach.setOriginalName(putFile.getOriginalName());
		attach.setAttachSize(fileSize);
		attach.setExtension(fileExtension);
		attachService.save(attach);
		return attach.getId();
	}

	/**
	 * 只让指定后缀的文件上传
	 */
	private void testExt(String fileName){
		if(!LocalFileUtil.testExt("image", fileName) && !LocalFileUtil.testExt("media", fileName)){
			throw new ServiceException("不支持的文件类型");
		}
	}

	/**
	 * 创建存储桶
	 *
	 * @param bucketName 存储桶名称
	 * @return Bucket
	 */
	@SneakyThrows
	@PostMapping("/make-bucket")
	@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	@ApiOperation(value = "", hidden = true)
	public R makeBucket(@RequestParam String bucketName) {
		ossBuilder.template().makeBucket(bucketName);
		return R.success("创建成功");
	}

	/**
	 * 创建存储桶
	 *
	 * @param bucketName 存储桶名称
	 * @return R
	 */
	@SneakyThrows
	@PostMapping("/remove-bucket")
	@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	@ApiOperation(value = "", hidden = true)
	public R removeBucket(@RequestParam String bucketName) {
		ossBuilder.template().removeBucket(bucketName);
		return R.success("删除成功");
	}

	/**
	 * 拷贝文件
	 *
	 * @param fileName       存储桶对象名称
	 * @param destBucketName 目标存储桶名称
	 * @param destFileName   目标存储桶对象名称
	 * @return R
	 */
	@SneakyThrows
	@PostMapping("/copy-file")
	@ApiOperation(value = "", hidden = true)
	public R copyFile(@RequestParam String fileName, @RequestParam String destBucketName, String destFileName) {
		ossBuilder.template().copyFile(fileName, destBucketName, destFileName);
		return R.success("操作成功");
	}

	/**
	 * 获取文件信息
	 *
	 * @param fileName 存储桶对象名称
	 * @return InputStream
	 */
	@SneakyThrows
	@GetMapping("/stat-file")
	@ApiOperation(value = "", hidden = true)
	public R<OssFile> statFile(@RequestParam String fileName) {
		return R.data(ossBuilder.template().statFile(fileName));
	}

	/**
	 * 获取文件相对路径
	 *
	 * @param fileName 存储桶对象名称
	 * @return String
	 */
	@SneakyThrows
	@GetMapping("/file-path")
	@ApiOperation(value = "", hidden = true)
	public R<String> filePath(@RequestParam String fileName) {
		return R.data(ossBuilder.template().filePath(fileName));
	}


	/**
	 * 获取文件外链
	 *
	 * @param fileName 存储桶对象名称
	 * @return String
	 */
	@SneakyThrows
	@GetMapping("/file-link")
	@ApiOperation(value = "", hidden = true)
	public R<String> fileLink(@RequestParam String fileName) {
		return R.data(ossBuilder.template().fileLink(fileName));
	}

	/**
	 * 上传文件
	 *
	 * @param fileName 存储桶对象名称
	 * @param file     文件
	 * @return ObjectStat
	 */
	@SneakyThrows
	@PostMapping("/put-file-by-name")
	@ApiOperation(value = "", hidden = true)
	public R<PutFile> putFile(@RequestParam String fileName, @RequestParam MultipartFile file) {
		PutFile putFile = ossBuilder.template().putFile(fileName, file.getInputStream());
		return R.data(putFile);
	}

	/**
	 * 删除文件
	 *
	 * @param fileName 存储桶对象名称
	 * @return R
	 */
	@SneakyThrows
	@PostMapping("/remove-file")
	@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	@ApiOperation(value = "", hidden = true)
	public R removeFile(@RequestParam String fileName) {
		ossBuilder.template().removeFile(fileName);
		return R.success("操作成功");
	}

	/**
	 * 批量删除文件
	 *
	 * @param fileNames 存储桶对象名称集合
	 * @return R
	 */
	@SneakyThrows
	@PostMapping("/remove-files")
	@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	@ApiOperation(value = "", hidden = true)
	public R removeFiles(@RequestParam String fileNames) {
		ossBuilder.template().removeFiles(Func.toStrList(fileNames));
		return R.success("操作成功");
	}

}
